<template>
    <!-- 任务表单开始 -->
    <div v-for="(task, tIndex) in tasks" :key="tIndex" class="sjplatform-form-edit-item">
        <el-form-item :key="task.id" :label="'任务' + (tIndex + 1) + '：'">
            <el-input class="item-input" v-model="task.taskName" placeholder="请输入任务名称" />
            <el-tooltip :content="'删除任务' + (tIndex + 1)" placement="bottom" effect="light">
                <i class="del-icon" @click="delSchedule(tIndex)"></i>
            </el-tooltip>
        </el-form-item>
        <el-form-item label="描述：">
            <el-input v-model="task.mark" type="textarea" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="父级：" v-if="task.sort > 1">
            <el-select v-model="task.pId" clearable placeholder="请选择父级任务"
                @update:modelValue="setSchedulePName(task, task.pId)">
                <el-option v-for="r in tasks.filter(r => r.id !== task.id && r.sort < task.sort && r.taskName != '')"
                    :key="r.id" :label="r.taskName" :value="r.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="计划时间：">
            <el-date-picker v-model="task.startTime" clearable type="date" placeholder="开始日期" />~<el-date-picker
                v-model="task.endTime" clearable type="date" placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="关联需求：">
            <el-input v-model="task.rName" readonly @click="showRequirementTree(tIndex, 'r')" placeholder="点击选择需求" />
        </el-form-item>
        <el-form-item label="关联功能：">
            <el-input v-model="task.fTitle" readonly @click="showRequirementTree(tIndex, 'f')" placeholder="点击选择功能" />
        </el-form-item>
        <el-form-item label="负责人：">
            <el-input v-model="task.personNames" placeholder="点击选择负责人"
                @click="openUserSelectForm('选择任务负责人', false, tIndex)" clearable @clear="clearpersons" />
        </el-form-item>
    </div>
    <!-- 任务表单结束 -->

    <el-form label-width="100px">
        <el-form-item label="任务操作：">
            <el-tooltip content="添加任务" placement="bottom" effect="light">
                <i class="add-icon" @click="addScheduleItem"></i>
            </el-tooltip>
            <el-tooltip content="导入任务" placement="bottom" effect="light">
                <i class="import-icon"></i>
            </el-tooltip>
            <el-tooltip content="生成进度计划文档" placement="bottom" effect="light">
                <i class="build-icon"></i>
            </el-tooltip>
        </el-form-item>
        <el-form-item label="附件：">
            <FileUpload ref="fileUpload" :historyFileList="historyFileList" @file-delete="handleFileDeleted" />
        </el-form-item>
    </el-form>

    <el-dialog v-model="newRTVisible" title="选择关联需求" width="30%" draggable :destroy-on-close="true"
        :close-on-click-modal="false" class="fullscreen-dialog">
        <RequirementTree ref="rTreeRef" :projectId="projectStore.scheduleModel.projectId" />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="isOpenUserSelectForm" :title="formTitle" width="50%" draggable :destroy-on-close="true">
        <UserSelect :initSelectedUser="initSelectedUser" />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isOpenUserSelectForm = false; indexTmp = 0;">取消</el-button>
                <el-button type="primary" @click="confirmPerson">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, reactive } from 'vue';
import FileUpload from "../../Common/FileUpload.vue";
import { useProjectTable } from "../../../hooks/ProjectManager/Start/useProjectTable";
import { useProjectSchedule } from "../../../hooks/ProjectManager/Plan/useProjectSchedule";
import RequirementTree from '../Common/RequirementTree.vue';
import UserSelect from "../../../components/SystemManager/User/UserSelect.vue";
import commonUtil from '../../../utils/common';
import emitter from "../../../utils/emitter";

let historyFileList = ref();
let newRTVisible = ref(false);
let rTreeRef = ref(null);
let indexTmp = 0;//临时存储任务索引
let { projectTable, projectStore, getProjectDoc, deleteProjectDoc } = useProjectTable(1, 10);
let { getScheduleDetailByProjectId, getScheduleDetailByScheduleId } = useProjectSchedule(1, 10);

// console.log('receivedProps',receivedProps.requirements)

//接收参数
let receivedProps = defineProps({
    modelValue: Array,
    sId: String,
    changeRequirements: Array,
    changeType: Number
});

let emit = defineEmits(['update:modelValue']);
//父组件传递的有值则用父组件的，没有则为空数组
let tasks = ref([]);

// 监听局部数据的变化并发出更新事件，确保双向绑定
watch(tasks, (newValue) => {
    emit('update:modelValue', newValue);
}, { deep: true });

// 监听 变更需求的变化，当 changeRequirements 更新时同步到局部数据
watch(() => receivedProps.changeRequirements, (newValue) => {
    tasks.value = [];
    createTaskFromRequirement(newValue);
}, { deep: true });

function createTaskFromRequirement(requirements: any) {
    if (requirements) {
        //先遍历需求
        for (let requirement of requirements) {
            let r = requirement as any;
            let task = {
                id: commonUtil.Methods.generateGUID(),
                projectId: projectStore.projectModel.id,
                mId: projectStore.scheduleModel.id,
                taskName: r.title,
                mark: '',
                pId: '',
                pName: '',//父级任务
                rId: r.id,
                rName: r.title,
                fId: '',
                fTitle: '',
                sort: tasks.value.length + 1,//排序
                startTime: null,//开始时间
                endTime: null,//结束时间
                personIds: '',
                personNames: '',
                persons: [],//负责人
                personsSelected: [],//选中的负责人
            }
            tasks.value.push(task);

            //判断是否有功能，如果有则遍历
            if (r.childFeatures) {
                for (let feature of r.childFeatures) {
                    let f = feature as any;
                    //父级功能
                    let pf = r.childFeatures.filter(p => p.id == f.pId);

                    //父级任务
                    let pt;
                    if (pf.length > 0 && pf[0].id) {
                        pt = tasks.value.filter(t => t.fId == pf[0].id);
                    }

                    tasks.value.push(
                        {
                            id: commonUtil.Methods.generateGUID(),
                            projectId: projectStore.projectModel.id,
                            mId: projectStore.scheduleModel.id,
                            taskName: f.title,
                            mark: '',
                            pId: pt && pt.length > 0 && pt[0].id ? pt[0].id : task.id,
                            pName: pt && pt.length > 0 && pt[0].taskName ? pt[0].taskName : task.taskName,//父级任务
                            rId: r.id,
                            rName: r.title,
                            fId: f.id,
                            fTitle: f.title,
                            sort: tasks.value.length + 1,//排序
                            startTime: null,//开始时间
                            endTime: null,//结束时间
                            personIds: '',
                            personNames: '',
                            persons: [],//负责人
                            personsSelected: [],//选中的负责人
                        }
                    );
                }
            }
        }
    }
}

// if (projectStore.scheduleModel.projectId) {
//     getScheduleDetailByProjectId(projectStore.scheduleModel.projectId).then(() => {
//         //如果任务主表ID为空则表示还没有配置，生成一个主ID并给projectId赋值
//         if (!projectStore.scheduleModel.id) {
//             projectStore.scheduleModel.id = commonUtil.Methods.generateGUID();
//             projectStore.scheduleModel.projectId = projectStore.projectModel.id;
//         }
//     })
// }

//根据进度ID获取进度详情
if (receivedProps.sId) {
    getScheduleDetailByScheduleId(receivedProps.sId);
}

//附件
if (projectStore.projectModel.id) {
    getProjectDoc(projectStore.projectModel.id, 2).then(() => {
        historyFileList.value = projectTable.documentList;
    });
}

/*--------------------选择负责人开始--------------------*/
let isOpenUserSelectForm = ref(false); //是否打开用户选择窗口
let formTitle = ref("");
let initSelectedUser = reactive({
    single: false,
    selectedrow: [],
});
//打开人员选择窗口
function openUserSelectForm(title, value, index) {
    formTitle.value = title;
    indexTmp = index;
    initSelectedUser.single = value;
    initSelectedUser.selectedrow = tasks.value[indexTmp].personIds.split(',');
    isOpenUserSelectForm.value = true;
}
//清理负责人
function clearpersons() {
    tasks.value[indexTmp].presonNames = '';
    tasks.value[indexTmp].personIds = '';
    tasks.value[indexTmp].persons = [];
    tasks.value[indexTmp].personsSelected = [];
}
//确认选择的负责人
function confirmPerson() {
    emitter.emit("confirmSelectedUser");
}
//供用户选择调用设置选择的项
emitter.on("set-selected-user", (SelectionRows: any) => {
    let selectedUserId = [];
    let selectedUserName = [];
    clearpersons();
    for (let item of SelectionRows) {
        selectedUserId.push(item.id);
        selectedUserName.push(item.realName);
        tasks.value[indexTmp].persons.push({ userId: item.id, userName: item.realName });
    }
    tasks.value[indexTmp].personsSelected = selectedUserId;

    tasks.value[indexTmp].personNames = selectedUserName.join(",");
    tasks.value[indexTmp].personIds = selectedUserId.join(",");

    isOpenUserSelectForm.value = false;
    indexTmp = 0;
});
/*--------------------选择负责人结束--------------------*/

/*--------------------任务处理开始--------------------*/
//添加任务
function addScheduleItem() {
    // 添加新的任务对象
    tasks.value.push({
        id: commonUtil.Methods.generateGUID(),
        projectId: projectStore.projectModel.id,
        mId: projectStore.scheduleModel.id,
        taskName: '',
        mark: '',
        pId: '',
        pName: '',//父级任务
        rId: '',
        rName: '',
        fId: '',
        fTitle: '',
        sort: tasks.value.length + 1,//排序
        startTime: null,//开始时间
        endTime: null,//结束时间
        personIds: '',
        personNames: '',
        persons: [],//负责人
        personsSelected: [],//选中的负责人
    });
}
//删除任务
function delSchedule(reqIndex) {
    // 向指定任务的子项列表中添加新子项
    tasks.value.splice(reqIndex, 1);
}

//设置任务父级名称
function setSchedulePName(item, value) {
    // 找到对应的父级任务
    const parent = tasks.value.find(r => r.id === value);
    // 如果找到了父级任务，设置 pId 和 pName
    if (parent) {
        item.pId = parent.id;
        item.pName = parent.taskName;
    }
}
/*--------------------任务处理结束--------------------*/

/*--------------------关联需求开始--------------------*/
let selectType = ref('r');//是选择需求还是功能，r=需求，f=功能
//显示需求树
function showRequirementTree(index, type) {
    if (receivedProps.changeType == 1) //新增的没有关联的需求，是默认从变更的需求中同步过来的
    {
        return;
    }
    newRTVisible.value = true;
    selectType.value = type;
    indexTmp = index;
}
//取消关联需求
function cancel() {
    indexTmp = 0;
    newRTVisible.value = false;
}

//确定关联需求
function confirm() {
    if (selectType.value == 'r') {
        tasks.value[indexTmp].rId = rTreeRef.value.exposeNode.id;
        tasks.value[indexTmp].rName = rTreeRef.value.exposeNode.value;
    }
    if (selectType.value == 'f') {
        //需求
        tasks.value[indexTmp].rId = rTreeRef.value.exposeNode.rId;
        tasks.value[indexTmp].rName = rTreeRef.value.exposeNode.rName;
        //功能
        tasks.value[indexTmp].fId = rTreeRef.value.exposeNode.id;
        tasks.value[indexTmp].fTitle = rTreeRef.value.exposeNode.value;
    }
    indexTmp = 0;
    newRTVisible.value = false;
}
/*--------------------关联需求结束--------------------*/

// 处理文件删除事件
async function handleFileDeleted(objectId) {
    if (await deleteProjectDoc(objectId)) {
        historyFileList.value = historyFileList.value.filter(file => file.objectId !== objectId);
    }
}
</script>